<template>
  <div class="app-container" ref="appContainerRef" style="height: 100%">
    <div class="header">
      <div>
        <el-input v-model="query.name" placeholder="请输入题目名称" style="width: 200px;" class="mr-10" clearable />
        <el-select v-model="query.teams_group_id" placeholder="请选择班组" clearable style="width: 200px" class="mr-10">
          <el-option v-for="item in groupsList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="success" @click="add">新增</el-button>
      </div>

    </div>
    <div class="mian">
      <el-table v-loading="loading" :data="list" border stripe fit highlight-current-row style="width: 100%"
        :height="tableHeight" ref="tableRef" :header-cell-style="{ background: '#ECF1FE', color: '#606266' }">
        <el-table-column label="姓名" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="age" width="80">
          <template slot-scope="{row}">
            <span>{{ row.age ? row.age : "/" }}</span>

          </template>
        </el-table-column>
        <el-table-column label="班组" align="teams_group_id" width="80">
          <template slot-scope="{row}">
            <span>{{ getGroup(row.teams_group_id) }}</span>

          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center">
          <template slot-scope="{row}">
            <span>{{ row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否通过三级教育" align="center" width="80">
          <template slot-scope="{row}">
            <el-tag v-if="row.pass_three == 1" type="success">通过</el-tag>
            <el-tag v-if="row.pass_three == 0" type="danger">未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="照片" align="center">
          <template slot-scope="{row}">
            <el-image style="height: 50px" :src="row.photo" :preview-src-list="[row.photo]" v-if="row.photo">
            </el-image>
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证" align="center">
          <template slot-scope="{row}">
            <span>{{ row.id_card }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="{row}">
            <el-button type="primary" @click="edit(row)">编辑</el-button>
            <el-button type="danger" @click="del(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px 0px;display: flex;justify-content: end;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog :visible="dialogVisible" title="新增人员" @close="closeDialog" width="500px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px" label-position="left" :rules="rules"
        :close-on-click-modal="false">
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim.number="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.trim.number="form.age"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="id_card">
          <el-input v-model.trim.number="form.id_card"></el-input>
        </el-form-item>
        <el-form-item label="通过三级教育" prop="pass_three">
          <el-radio-group v-model="form.pass_three">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班组" prop="teams_group_id">
          <el-select v-model="form.teams_group_id" placeholder="请选择班组" clearable>
            <el-option v-for="item in groupsList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="照片">
          <div style="display:flex">
            <img v-if="form.photo" :src="form.photo" class="avatar">
            <el-upload class="avatar-uploader" action="/api/upload/uploadFiles" :show-file-list="false"
              :on-success="handleAvatarSuccess" name="photo" ref="uploadRef" list-type="picture-card"
              :on-change="handleFileChange">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { debounce } from "@/utils/index"
import { personCreate, getPersonInfo, getPersonList, delPersonInfo } from "@/api/user"
export default {
  data() {
    // 自定义手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      const reg = /^1[3-9]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('请输入有效的手机号码'));
      } else {
        callback();
      }
    };
    // 自定义年龄验证规则
    const validateAge = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('年龄不能为空'));
      }
      if (!Number.isInteger(value) || value < 1 || value > 100) {
        callback(new Error('请输入1-100之间的整数'));
      } else {
        callback();
      }
    };
    // 简化验证规则（基础格式验证）
    const checkIdCard = (rule, value, callback) => {
      if (!value) return callback(new Error('不能为空'));

      // 基础正则验证（验证长度和基本格式）
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/;

      if (!reg.test(value)) {
        callback(new Error('身份证格式不正确'));
      } else {
        callback();
      }
    };
    return {
      query: {
        teams_group_id: "",
        name: "",
      },
      loading: false,
      list: [],
      pagination: {
        currentPage: 1,
        total: 0,
        pageSize: 10,
      },
      tableHeight: 500,
      dialogVisible: false,
      form: {
        name: "",
        phone: "",
        id_card: "",
        pass_three: 0,
        photo: "",
        age: null,
        teams_group_id: null,
      },
      rules: {
        name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
        // phone: [{
        //   validator: validatePhone
        // }],
        // age: [{
        //   validator: validateAge
        // }],
        // id_card: [
        //   { validator: checkIdCard, trigger: 'blur' }
        // ]
      },
      groupsList: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.setTableHeight()
      window.onresize = () => {
        debounce(this.setTableHeight(), 200, true)
      }
    })
    this.getList()
    this.groupsList = this.$groupsList;
  },
  methods: {
    getList() {
      let data = { ...this.pagination, ...this.query }
      console.log(1111, data)
      getPersonList(data).then((res) => {
        console.log(2222, res.data.rows)
        this.list = res.data.rows;
        this.pagination = res.data.pagination;
      })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getList()
    },
    setTableHeight() {
      let offsetHeight = this.$refs.appContainerRef.offsetHeight;
      this.tableHeight = offsetHeight - 20 - 33 - 20 - 50;
      this.$refs.tableRef.doLayout()
    },
    edit(row) {
      getPersonInfo({ id: row.id }).then((res) => {
        console.log(111111, res.data)
        if (res.code == 200) {
          this.dialogVisible = true;
          this.form = {
            ...res.data
          }
        }
      })
    },
    del(row) {
      this.$confirm('是否删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPersonInfo({ id: row.id }).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }
        })

      })

    },
    search() {
      this.pagination = {
        currentPage: 1,
        total: 0,
        pageSize: 10,
      },
        this.getList()
    },
    add() {
      this.dialogVisible = true;
    },
    clear() {
      this.form = {
        name: "",
        phone: "",
        id_card: "",
        pass_three: 0,
        photo: "",
        age: null,
        teams_group_id: null,
      }
    },
    closeDialog() {
      this.dialogVisible = false;
      this.clear()
      this.$refs.form.resetFields()
      // this.$refs.uploadRef.clearFiles();
      console.log(1111, this.form)
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          personCreate({
            name: "",
            phone: Number(this.form.phone),
            id_card: Number(this.form.id_card),
            pass_three: 0,
            photo: "",
            age: Number(this.form.age),
            teams_group_id: Number(this.form.teams_group_id),
            ...this.form
          }).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.getList()
              this.$message({
                message: res.message,
                type: 'success'
              })
            }
          })
        }
      });
    },
    handleAvatarSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.form.photo = res.data.filesUrl;
        this.$message({
          message: "照片上传成功",
          type: 'success'
        })
      } else {
        this.$message({
          message: "照片上传失败",
          type: 'error'
        })
      }
    },
    handleFileChange(file) {
      // this.form.photo = file.url
      // this.$message({
      //   message: "照片上传中，请稍后",
      //   type: 'info'
      // })
    },
    getGroup(id) {
      let title;
      this.$groupsList.forEach(item => {
        if (item.value == id) {
          title = item.label;
        }
      });
      return title
    }
  },
}
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  margin-right: 10px;
}

.upload-wrap {
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>